// customDBVariable.cpp: implementation of the CustomDBVariable class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "customDBVariable.h"
#include "PropertyVisitor.h"
#include "SimpleExpression.h"
#include "Part.h"
#include "ProductCatalogManager.h"
#include "DBConnectionManager.h"
#include "RecordsetPtrWrap.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

using namespace JointSystem;
using namespace DAWrapper;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
namespace PropertySystem
{
	CustomDBVariable::CustomDBVariable()
	{
		PropertVar(this);
		m_bIsCustom = TRUE;
	}
	
	CustomDBVariable::~CustomDBVariable()
	{
		
	}
	
	BOOL CustomDBVariable::Accept(PropertyVisitor& visitor)
	{
		return visitor.Visit(this);
	}

	PropertyVariable* CustomDBVariable::Clone()
	{
		CustomDBVariable* pVar = new CustomDBVariable;
		ASSERT_MEMORY_VALID(pVar, NULL);

		this->CopyCustomData(*pVar, *this);
		this->CopyPropertyData(*pVar, *this);
		pVar->PropertyTable(this->PropertyTable());
		pVar->PropertyField(this->PropertyField());
		return pVar;
	}

	void CustomDBVariable::UpdateData()
	{
		m_EffectData.RemoveAll();
		if(PromptSource().IsEmpty())
			return;

		SimpleExpression expr(PromptSource(), GetOwner()->GetPropertyStack());

		Variable var = expr.Caculate();

		CString strSql;
		strSql = (CString)var;
		
		ProductCatalog* pCatalog = NULL;
		pCatalog = ProductCatalogManager::Instance()->GetProductCatalog(static_cast<Part*>(GetOwner())->GetStandard());
		ASSERT(pCatalog);

		CString strSource = pCatalog->DataSourceURI();
		ASSERT(!strSource.IsEmpty());

		_ConnectionPtr& pCon = *DBConnectionManager::Instance()->GetConnectionPtrByUri(strSource);

		RecordsetPtrWrap rs;
		rs.Set(strSql, pCon);
		while(!rs.IsBOF() && !rs.IsEOF())
		{
			m_EffectData.Add(rs.GetString(this->PropertyField()));
			rs.MoveNext();
		}
	}
}
